"""
文件上传工具
处理文件上传和存储
"""
import os
import uuid
from datetime import datetime
from werkzeug.utils import secure_filename
from flask import current_app

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'xlsx', 'xls', 'csv'}

def allowed_file(filename):
    """检查文件类型是否允许"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_file(file, folder='general'):
    """保存上传的文件
    
    Args:
        file: 文件对象
        folder: 存储子文件夹名，默认为general
        
    Returns:
        str: 文件在服务器上的相对路径
    """
    if not allowed_file(file.filename):
        raise ValueError("文件类型不允许")
    
    # 创建安全的文件名
    filename = secure_filename(file.filename)
    # 添加时间戳和随机字符串确保唯一性
    new_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}_{filename}"
    
    # 创建存储路径
    upload_folder = os.path.join(current_app.config['UPLOAD_FOLDER'], folder)
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)
    
    # 保存文件
    file_path = os.path.join(upload_folder, new_filename)
    file.save(file_path)
    
    # 返回文件的相对路径
    relative_path = os.path.join(folder, new_filename)
    return relative_path

def delete_file(file_path):
    """删除上传的文件
    
    Args:
        file_path: 文件相对路径
    
    Returns:
        bool: 是否删除成功
    """
    absolute_path = os.path.join(current_app.config['UPLOAD_FOLDER'], file_path)
    if os.path.exists(absolute_path):
        os.remove(absolute_path)
        return True
    return False 